package com.example.compose.retrofit

import android.content.Context
import android.content.pm.PackageManager
import android.net.TrafficStats
import com.example.compose.BuildConfig.APPLICATION_ID
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory


object NetWorkManager {

    private val retrofit: Retrofit

    init {
        val loggingInterceptor =  Interceptor{ chain ->
            val originalResponse = chain.proceed(chain.request())
            return@Interceptor originalResponse.newBuilder().header("token", "").build()
        }

        val client: OkHttpClient = OkHttpClient.Builder()
//            .addInterceptor(loggingInterceptor)
//            .connectTimeout(10, TimeUnit.SECONDS)
//            .readTimeout(10, TimeUnit.SECONDS)
            .build()

        retrofit=Retrofit.Builder()
            .client(client)
            .baseUrl("http://api.e-toys.cn/api/")
            .addConverterFactory(GsonConverterFactory.create())
            .build()
    }

    fun getRequest(): ApiService = retrofit.create(ApiService::class.java)

    // 获取应用程序的 uid
    private fun getAppUid(context:Context): Int {
        var uid = -1
        val packageManager: PackageManager = context.packageManager
        try {
            val applicationInfo = packageManager.getApplicationInfo(
                APPLICATION_ID,
                PackageManager.GET_META_DATA
            )
            uid = applicationInfo.uid
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return uid
    }

    private var lastTotalRxBytes: Long = 0
    private var lastTimeStamp: Long = 0
    private var result = 0
    private var lastTime = 0L

    /**
     * 获取网络下载速度
     * @param uid
     * @return
     */
    fun getNetSpeed(context:Context): String {
        val nowTotalRxBytes = getTotalRxBytes(getAppUid(context))
        val nowTimeStamp = System.currentTimeMillis()
        if(nowTimeStamp- lastTime > 1000){
            lastTime = nowTimeStamp
            val speed = (nowTotalRxBytes - lastTotalRxBytes) * 1000 / (nowTimeStamp - lastTimeStamp) //毫秒转换
            lastTimeStamp = nowTimeStamp
            lastTotalRxBytes = nowTotalRxBytes
            try {
                result = speed.toInt()
            } catch (e: Exception) {
            }
        }
        return speedFormat(result)
    }

    private fun getTotalRxBytes(uid: Int): Long {
        //转为KB
        return if (TrafficStats.getUidRxBytes(uid) == TrafficStats.UNSUPPORTED.toLong()) 0 else TrafficStats.getTotalRxBytes() / 1024
    }

    /**
     * 下载速度字符串格式化
     *
     * @param speed
     * @return
     */
    private fun speedFormat(speed: Int): String {
        val result: String = if (speed > 1024) {
            val partA = speed / 1024
            val partB = (speed - partA * 1024) / 100
            partA.toString() + "." + partB + "m/s"
        } else {
            speed.toString() + "kb/s"
        }
        return result
    }


}